package com.erb.controller.zwj.admin;

import com.erb.constants.AdminConstants;
import com.erb.entity.IntegralGoods;
import com.erb.entity.RespBean;
import com.erb.service.zwj.IIntegralGoodsService;
import com.erb.utils.file.FileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 后台积分商品Controller
 */
@RestController
@RequestMapping("/admin/integral-goods")
public class AdminIntegralGoodsController {
	@Resource
	private IIntegralGoodsService integralGoodsService;

	@GetMapping("/list")
	public ModelAndView list() {
		return new ModelAndView("admin/integral-goods/list");
	}

	@GetMapping("/add-goods")
	public ModelAndView addGoods() {
		return new ModelAndView("admin/integral-goods/add-goods");
	}

	@GetMapping("/edit-goods/{goodsId}")
	public ModelAndView editGoods(@PathVariable("goodsId") Integer goodsId) {
		ModelAndView modelAndView = new ModelAndView("admin/integral-goods/edit-goods");
		modelAndView.addObject("goods", integralGoodsService.findGoodsById(goodsId));
		return modelAndView;
	}

	@GetMapping("/listJson")
	public RespBean listJson() {
		try {
			Thread.sleep(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return RespBean.ok("查询成功！", integralGoodsService.findAllGoodsForList());
	}

	@PostMapping("/save")
	public RespBean save(IntegralGoods integralGoods, @RequestParam("goodsImg") MultipartFile imgFile) {
		// 图片路径
		if (null != imgFile && !imgFile.isEmpty()) {
			String newName = FileUpload.uploadAndRename(AdminConstants.ADVERTISEMENT_SAVE_PATH, imgFile);
			integralGoods.setImg(newName);
		}

		if (integralGoodsService.save(integralGoods)) {
			return RespBean.ok("保存成功！", integralGoods);
		} else {
			return RespBean.error("保存失败，请重试！");
		}
	}

	@PostMapping("/edit")
	public RespBean edit(IntegralGoods integralGoods, @RequestParam("goodsImg") MultipartFile imgFile) {
		// 图片路径
		if (null != imgFile && !imgFile.isEmpty()) {
			String newName = FileUpload.uploadAndRename(AdminConstants.ADVERTISEMENT_SAVE_PATH, imgFile);
			integralGoods.setImg(newName);
		} else {
			integralGoods.setImg(null);
		}
		if (integralGoodsService.modify(integralGoods)) {
			return RespBean.ok("修改成功！", integralGoodsService.findGoodsById(integralGoods.getId()));
		} else {
			return RespBean.error("修改失败，请重试！");
		}
	}

	@DeleteMapping("/remove")
	public RespBean remove(@RequestParam("id") Integer goodsId) {
		return RespBean.ok("删除成功！", integralGoodsService.remove(goodsId));
	}

	@PostMapping("/changeGoodsState")
	public RespBean changeGoodsState(@RequestBody Map<String, Object> map) {
		int id = (int) map.get("uniqueIdentity");
		boolean state = (boolean) map.get("s");
		return RespBean.ok("更改成功！", integralGoodsService.modifyGoodsStateById(id, state));
	}
}
